package com.ar4j.type;

import java.sql.Types;

/**
 * Converter class providing ability to convert from an Enum to its string name and back.
 */
public class EnumTypeConverter<E extends Enum<E>> implements ITypeConverter<E, String> {
  private Class<E> enumClass;
  
  @Override
  public String convertToStorage(E value) {
    return (value == null ? null : value.name());
  }

  @Override
  public E convertFromStorage(String storageValue) {
    if(enumClass == null) {
      throw new UnsupportedOperationException("Cannot call convertFromStorage before calling setTypes");
    }
    
    return (storageValue == null ? null : Enum.valueOf(enumClass, storageValue));
  }

  @Override
  public int getSqlType() {
    return Types.VARCHAR;
  }
  
  @Override
  public Class<E> getObjectType() {
    return enumClass;
  }

  @Override
  public Class<String> getStorageType() {
    return String.class;
  }
  
  @Override
  public void setTypes(Class<E> objectType, Class<String> storageType) {
    if(enumClass != null) {
      throw new IllegalArgumentException("setTypes cannot be called twice on this EnumTypeConverter");
    } else if (storageType != null) {
      throw new IllegalArgumentException("Setting the storageType is not allowed for EnumTypeConverter");
    } else {
      enumClass = objectType;
    }
  }

}
